package com.bwie.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2025-05-21 13:44:09
 */
@Service
@Slf4j
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
        implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    FastFileStorageClient fastFileStorageClient;


    @Override
    public Result login(LoginVo loginVo) {


        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUsername, loginVo.getUsername())
        );

        if (tbUser == null) {
            return Result.error().setMsg("用户不存在");
        }

//        String encrypt = MD5Utils.encrypt(loginVo.getPassword());
        String encrypt = DigestUtil.md5Hex(loginVo.getPassword());
        log.info("加密的密码为：" + encrypt);
        if (!tbUser.getPassword().equals(encrypt)) {
            return Result.error().setMsg("密码错误");
        }


        String tokenKey = "token-" + tbUser.getUserId();
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("realName", tbUser.getRealName())
                .claim("mobile", tbUser.getMobile()).compact();


        redisTemplate.opsForValue().set(tokenKey, token, 15, TimeUnit.MINUTES);

        tbUser.setPassword(null);
        tbUser.setToken(token);

        return Result.ok().setData(tbUser);
    }

    @Override
    public List getMenuList(Integer userId) {

        List<TbMenu> tbMenuList = tbUserMapper.getMenuList(userId);

        List<Tree<String>> treeList = TreeUtil.build(tbMenuList, "0", (menu, tree) -> {

            tree.setParentId(menu.getMenuPid() + "");
            tree.setId(menu.getMenuId() + "");
            tree.setName(menu.getMenuName());
            tree.putExtra("path", menu.getMenuPath());

        });

        return treeList;
    }

    @Override
    public Result getUserList(PageInfoVo pageInfoVo) {

        Page<TbUser> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());


        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
            wrapper.lambda().like(TbUser::getRealName, pageInfoVo.getKeyWord())
                    .or().like(TbUser::getMobile, pageInfoVo.getKeyWord())
                    .or().like(TbUser::getEmail, pageInfoVo.getKeyWord());
        }
        if (pageInfoVo.getTypeId() != null) {
            wrapper.lambda().eq(TbUser::getSex, pageInfoVo.getTypeId());
        }

        if (StringUtils.isNotEmpty(pageInfoVo.getBeginTime())) {
            wrapper.lambda().ge(TbUser::getCreateTime, pageInfoVo.getBeginTime());
        }

        if (StringUtils.isNotEmpty(pageInfoVo.getEndTime())) {
            wrapper.lambda().le(TbUser::getCreateTime, pageInfoVo.getEndTime());
        }

        Page<TbUser> tbUserPage = tbUserMapper.selectPage(page, wrapper);

        return Result.ok().setData(tbUserPage);
    }

    @Override
    public Result updateByUserId(TbUser tbUser) {

        TbUser user = tbUserMapper.selectById(tbUser.getUserId());
        if (user == null) {
            return Result.error().setMsg("商户不存在");
        }

        tbUserMapper.updateById(tbUser);

        return Result.ok();

    }

    @Override
    public Result uploadImage(MultipartFile file) {
        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://192.168.10.131:8888/" + storePath.getFullPath();
            return Result.ok().setData(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().setMsg("上传失败");
        }
    }


    @Override
    public Result deleteUser(Integer userId) {

        TbUser tbUser = tbUserMapper.selectById(userId);

        if (tbUser == null) {
            return Result.error().setMsg("不存在");
        }

        tbUserMapper.deleteById(userId);

        return Result.ok();
    }

    @Override
    public Result deleteUserAll(List<TbUser> tbUserList) {

        for (TbUser tbUser : tbUserList) {

            tbUserMapper.deleteById(tbUser.getUserId());
        }
        return Result.ok();
    }

    @Override
    public Result checkUser(TbUser tbUser) {

        if (tbUser.getCheckStatus() == 2) {
            if (StringUtils.isEmpty(tbUser.getCheckReason())) {
                return Result.error().setMsg("请输入审核原因");
            }
        }

        TbUser user = tbUserMapper.selectById(tbUser.getUserId());
        if (user == null) {
            return Result.error().setMsg("用户不存在");
        }

        user.setCheckStatus(tbUser.getCheckStatus());
        user.setCheckReason(tbUser.getCheckReason());
        tbUserMapper.updateById(user);

        return Result.ok();
    }
}




